<template>
	<view class="page__content" :style="{ height: config.scrollHeight + 'px' }" style="overflow: hidden;">
		<view class="navBox">
			<up-navbar title="首页看板" style="z-index: 99;" left-icon="" :autoBack="false" :fixed="false"
				:safeAreaInsetTop="true">

				<template #left>
					<view class="boardSelect" @click="openBaseScreen('看板')">
						<text class="text">{{selectedBoard.boardTitle}}</text>
						<uni-icons fontFamily="CustomFontPlatform" :size="14" color="#fff">{{'\ue605'}}</uni-icons>
					</view>
				</template>
			</up-navbar>

		</view>

		<view :style="{height:scrollHeight+'px'}">
			<template v-if="!uni.$utils.isEmpty(selectedBoard.boardName)">
				<template v-if="selectedBoard.boardName == 'sale'">
					<Sale></Sale>
				</template>
				<template v-else-if="selectedBoard.boardName == 'purchase'">
					<Purchase></Purchase>
				</template>
				<template v-else-if="selectedBoard.boardName == 'warehouse'">
					<Warehouse></Warehouse>
				</template>


				<template v-else-if="selectedBoard.boardName == 'finance'">
					<Finance></Finance>
				</template>


				<template v-else-if="selectedBoard.boardName == 'ticket-1'">
					<kanban-ticket></kanban-ticket>
				</template>




			</template>

		</view>

	</view>
</template>

<script setup lang="ts" name="home-board">
	import { ref, onMounted, onUnmounted, computed, getCurrentInstance, nextTick, reactive } from 'vue';
	import { onLoad, onReady, onShow, onUnload } from "@dcloudio/uni-app";
	import useRequestQueue from '@/uni_modules/mc-ui/libs/http/UniversalRequestQueue';
	const { request, requestByUrl, onAllComplete, onError } = useRequestQueue();

	import { useMainStore, useInventoryStore, useUserStore, usePermissionStore } from '@/store';
	const inventoryStore = useInventoryStore();
	const mainStore = useMainStore();
	const userStore = useUserStore();
	const permissionStore = usePermissionStore();


	// ERP 看板
	import Sale from '/commonPage/kanban/erp/sale';
	import Purchase from '/commonPage/kanban/erp/purchase.vue';
	import Warehouse from '/commonPage/kanban/erp/warehouse.vue';
	import Finance from '/commonPage/kanban/erp/finance.vue';
	import kanbanTicket from '/commonPage/kanban/ticket/ticket.vue';

	// 定义所有可能看板的映射表
	const componentMap : Record<string, any> = {
		Sale,
		Purchase,
		Warehouse,
		Finance
	}

	// 类型定义
	interface Config {
		tabbarHeight ?: number;
		scrollHeight ?: number;
	}

	const { config = {
		tabbarHeight: 0,
		scrollHeight: 500
	} } = defineProps(['config']);

	console.log(config);

	const scrollHeight = ref(500);
	scrollHeight.value = config.scrollHeight;

	const UserInfo = computed<any>(() => {
		return userStore.UserInfo
	});

	// 当前选中看板信息
	let selectedBoard = ref<any>({
		boardTitle: "",
		boardID: 0,
		boardName: '',
	});
	let componentKey = ref<any>(null);
	// 动态组件计算属性
	const dynamicComponent = computed(() => {
		// 如果存在映射则返回对应组件，否则返回 null
		return componentMap[selectedBoard.value.boardName] || null
	})
	let routes = getCurrentPages(); //当前页面栈

	const baseScreenListenName = computed(() => {
		return 'home_choice_' + routes.length
	});

	console.log(baseScreenListenName.value);
	// 切换看板
	function openBaseScreen(str : string) {
		mainStore.openBaseScreen({
			allowClear: false, // 清除按钮
			cmd: '', // 接口名
			titleName: str,
			listeningName: baseScreenListenName.value, // 监听器
			multiple: false, // 是否开启多选
			serverSearch: { // 查询项
				format: { // 数据映射
					displayValue: "boardTitle", // 显示值
					hiddenValue: "boardName", // 隐藏值
				},
				isLocal: true, // 是否启用本地数据
				localData: boardList.value, // 当开启本地数据时使用
				isPaging: false, //是否分页
				choiceData: selectedBoard.value.boardName, // 选中数据
				choiceDataKey: "boardName", // 选中数据的key
			},
			param: { // 传递参数
			}
		});
	}

	const storageName = computed(() => {
		return {
			ActiveBoard: "ActiveBoard_" + UserInfo.value.Business,
			selectedComboInfo: "selectedComboInfo_" + UserInfo.value.Business
		}
	})
	let boardList = ref<any>([]);
	// 初始化看板
	const initKanBan = () => {

		// 获取缓存并解析
		const cachedBoardStr = uni.getStorageSync(storageName.value.ActiveBoard);
		const cachedBoard = cachedBoardStr ? JSON.parse(cachedBoardStr) : null;

		// 初始化选中看板
		let _selectedBoard = null;
		if (boardList.value.length) {
			const targetBoard = boardList.value.find((board : any) => board.boardID === cachedBoard?.boardID);
			_selectedBoard = targetBoard ? {
				...targetBoard
			} : {
				...boardList.value[0]
			};
		}
		// 更新状态（包含空列表保护）
		if (_selectedBoard) {
			selectedBoard.value = _selectedBoard;
			componentKey.value = Date.now();
			uni.setStorageSync(storageName.value.ActiveBoard, JSON.stringify(_selectedBoard));
		}
	}



	// 获取产品版本下属模块
	const getModule = () => {
		request({
			config: {
				baseURL: mainStore.appConfigInfo.IPAgreement + mainStore.appConfigInfo.serverIP + "/Frame/SqlData?cmdname="
			},
			url: 'SelectActivatedModule',
			method: 'POST',
			data: {
				AccountID: UserInfo.value.Business
			},
			success: (ret : any) => {
				let selectedComboInfo = {};
				// 但项模式不考虑帐套问题
				if (ret.status == 200) {
					const selectedComboInfo = ret.data.ds[0];
					// 获取当前版本下所有APP菜单
					getAllMenuData(selectedComboInfo.ModuleID, 1);
					// 获取当前版本看板列表
					getKanBanList();
				}

			}
		})
	};
	// 获取当前版本下所有APP菜单
	const getAllMenuData = (moduleID : number, option ?: any) => {
		request({
			config: {
				baseURL: mainStore.appConfigInfo.IPAgreement + mainStore.appConfigInfo.serverIP + "/Frame/SqlData?cmdname="
			},
			url: 'platform_getAppModule',
			method: 'POST',
			data: {
				AccountID: UserInfo.value.Business,
				UserID: UserInfo.value.UserID,
				ModuleID: moduleID,
			},
			success: (res : any) => {
				if (res.status == 200) {
					if (res.data.ds.length) {
						const modules = res.data.ds;
						const pages = res.data.ds1;
						const pagesByModule = new Map();
						// 预处理阶段：初始化选中状态并建立模块-页面映射
						pages.forEach((item : any) => {
							// 简化布尔值赋值
							item.IsChecked = !!item.IsShortcut;

							// 建立模块ID到页面的映射
							if (!pagesByModule.has(item.APPType)) {
								pagesByModule.set(item.APPType, []);
							}
							pagesByModule.get(item.APPType).push(item);
						});
						// 主处理阶段：遍历模块
						modules.forEach((module : any) => {
							// 获取当前模块相关页面（O(1)时间复杂度）
							const modulePages = pagesByModule.get(module.ModuleID) || [];

							// 构建树形结构（使用Map优化去重）
							const treeTypeMap = new Map();
							modulePages.forEach((page : any) => {
								if (!page.IsTabbar) {
									const key = page.TreeType;
									if (!treeTypeMap.has(key)) {
										treeTypeMap.set(key, {
											treeType: key,
											treeTypeName: page.TreeTypeName,
											pages: []
										});
									}
									treeTypeMap.get(key).pages.push(page);
								}
							});

							// 构建最终数据结构
							module.shortcuts = modulePages.filter((p : any) => p.IsShortcut);
							module.treeTypes = Array.from(treeTypeMap.values());
							module.authPages = modulePages;
						});
						// 存储菜单数据
						mainStore.appConfigInfo.APPModules = modules;



					}
				}

			},
			fail: (err : any) => {
				console.log(err);
				uni.$utils.hideLoading();
			}
		})
	};
	// 获取用户APP看板(平台首页)
	const getKanBanList = () => {
		request({
			config: {
				baseURL: mainStore.appConfigInfo.IPAgreement + mainStore.appConfigInfo.serverIP + "/Frame/SqlData?cmdname="
			},
			url: 'PlatForm_SelectKaanBan',
			method: 'POST',
			data: {
				UserID: UserInfo.value.UserID,
				KanBanType: 2 // 移动看板
			},
			success: (res : any) => {
				let data = res.data.ds;

				boardList.value = data.map((item : any) => ({
					boardID: item.KanBanID,
					boardName: item.Path.substring(item.Path.lastIndexOf('/') + 1),
					boardTitle: item.KanBanName
				}));
				// 初始化看板
				initKanBan();
			}
		})
	};
	// 切换看板
	const changeKanBan = (board : any) => {

		uni.setStorageSync(storageName.value.ActiveBoard, JSON.stringify(board));
	}



	const instance = getCurrentInstance() as any;
	const getScollHeightFun = () => {
		const query = uni.createSelectorQuery().in(instance.proxy);

		query.select('.navBox').boundingClientRect((data : any) => {
			if (data) {
				scrollHeight.value = config.scrollHeight - data.height;
			}
		}).exec();
	};


	getModule();




	onMounted(async () => {

		uni.$on(baseScreenListenName.value, (ret : any) => {
			console.log(ret);
			switch (ret.titleName) {
				case "看板":
					selectedBoard.value = {
						boardID: ret.data.boardID,
						boardName: ret.data.boardName,
						boardTitle: ret.data.boardTitle
					};
					componentKey.value = Date.now();
					changeKanBan(selectedBoard.value);

					break;
				default:
					break;
			}
		})
		await nextTick();
		getScollHeightFun();
	})

	onUnload(() => {
		uni.$off(baseScreenListenName.value)
	})
</script>

<style lang="scss" scoped>
	.boardSelect {
		display: flex;
		align-items: center;
		margin-left: 15rpx;
		padding: 0 20rpx;
		// height: px;
		font-size: 32rpx;
		font-weight: 500;
		background: rgba(0, 0, 0, .03);
		border-radius: 10rpx;

		.text {
			color: #fff;
			font-size: 28rpx;
			margin-right: 10rpx
		}
	}
</style>